public class Solution2 {
    public int tem;
    boolean[][] fg;
    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        tem=grid[row][col];
        fg=new boolean[grid.length][grid[0].length];
        fg[row][col]=true;
        dfs(grid,row,col,color);
        return grid;
    }
    public int[] dx={1,0,-1,0};
    public int[] dy={0,1,0,-1};
    private void dfs(int[][] grid, int a, int b, int color) {
        for (int i = 0; i < 4; i++) {
            int x=a+dx[i];
            int y=b+dy[i];
            if(x>=0 && x<grid.length && y>=0 && y<grid[0].length && grid[x][y]==tem && !fg[x][y]){
                if(x==0 || x==grid.length-1 || y==0 || y==grid[0].length-1){
                    grid[x][y]=color;
                }
                fg[x][y]=true;
                dfs(grid,x,y,color);
            }
        }
    }
}
